/**
 * Created by xlt on 2017/5/8.
 */
/**
 * Created by xlt on 2017/5/2.
 */
import React from "react";
import {connect} from "react-redux";
import cookie from "react-cookie";
import {fetchPosts, reset} from "../../actions";
import {Link} from "react-router";
import ReactDOM from 'react-dom';

class login extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            countDown: 60,
            showSendButton : "",
            showTimeButton: "none",
            timeText: "重新发送(60)",
            isLogin: false,
            intervalId: 0
        }
    }

    componentWillMount() {
        document.title = "用户登录";
    }

    componentDidMount() {
        this.props.dispatch(reset("sendValidateCode"))
        this.props.dispatch(reset("userLogin"))
    }

    componentWillUnmount() {
        clearInterval(this.state.intervalId);
    }

    componentWillReceiveProps(nextProps) {
        console.log("errorCode" + nextProps.validateCode.errorCode);
        if (nextProps.validateCode.errorCode == 0) {
            alert("码证码发送成功");
            this.setState({
               showSendButton: "none",
               showTimeButton: ""
            })
            this.handleClick();
        }
        if(nextProps.loginResponse.errorCode == 0) {
            alert("登录成功");
            window.location.href = "/#/mall/index?token=" + nextProps.loginResponse.data.token;
        } else {
            this.setState({isLogin: false});
        }
    }

    sendCode() {
        let phone = ReactDOM.findDOMNode(this.refs.phoneNumber).value;
        if(phone == ""){
           alert("请输入手机号码");
           return;
        }
        const header = {"X-Client-ID": "123456"}
        this.props.dispatch(fetchPosts("sendValidateCode", header, {phoneNumber: phone}));
        this.props.dispatch(reset("sendValidateCode"))
    }

    handleClick(){
        let timer = setInterval(function () {
            let countDown = this.state.countDown;
            countDown--
            if (countDown < 1) {
                this.setState({
                    timeText: "重新发送(60)",
                    showSendButton : "",
                    showTimeButton: "none",
                    countDown : 60
                })
                clearInterval(this.state.intervalId);
            } else {
                this.setState({
                    timeText: "重新发送(" + countDown + ")",
                    showSendButton : "none",
                    showTimeButton: "",
                    countDown : countDown
                });
            }
        }.bind(this), 1000);

        this.setState({
            intervalId : timer
        })
    }

    login() {
        if(this.state.isLogin) {
            return;
        }
        let phone = ReactDOM.findDOMNode(this.refs.phoneNumber).value;
        let code = ReactDOM.findDOMNode(this.refs.codeNumber).value;
        if(phone == ""){
            alert("请输入手机号码");
            return;
        }

        if(code == "") {
            alert("请输入验证码");
            return;
        }

        const header = {"X-Client-ID": "123456"}
        let body = {
            userAccount:phone,
            accountType:0,
            validateCode:code,
            deviceType:1,
            pushType:1,
            longitude:"120.24698100000",
            latitude:"29.97432100000",
            pushClientId:"4cb0495f73fab55b3f100b87b1d212e982f5270d0d5b1f6b28008b7c50a42a30"
        }
        this.props.dispatch(reset("sendValidateCode"))
        this.props.dispatch(fetchPosts("userLogin", header, body));
        this.setState({isLogin:true})
    }

    render() {
        return (
            <div>
                <div className="login-tip">
                    您需要先登录，才能继续
                </div>
                <div className="login-div">
                    <input type="number" name="phoneNumber" placeholder="请输入手机号" ref="phoneNumber" className="login-input-phone"/>
                    <div className="login-code-div">
                        <input type="number" name="codeNumber" placeholder="请输入验证码" ref="codeNumber" className="login-input-code"/>
                        <input type="text" name="sendCode" value="发送验证码" readOnly="true"
                               onClick={this.sendCode.bind(this)} style={{display: this.state.showSendButton}}
                               className="login-send-code"/>
                        <input type="text" name="nextTime" value={this.state.timeText}
                               readOnly="true" style={{display: this.state.showTimeButton}}
                               className="login-send-code"/>
                    </div>
                </div>
                <div className="login-button">
                    <Link onClick={this.login.bind(this)}>登录</Link>
                </div>
            </div>
        );
    }

}

function mapStateToProps(state) {
    const {postsByApi} = state;
    const {
        isFetching,
        items: validateCode
    } =  postsByApi["sendValidateCode"] || {
        isFetching: false,
        items: {}
    };

    const {
        items: loginResponse
    } = postsByApi["userLogin"] || {
        items: {}
    }
    return {
        isFetching,
        validateCode,
        loginResponse
    };
}

export default connect(mapStateToProps)(login);